﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using UtilZ.Dotnet.Ex.Log;
using UtilZ.Dotnet.WindowsDesktopEx.Base;

namespace DotnetWinFormApp
{
    public partial class FCrush : Form
    {
        public FCrush()
        {
            InitializeComponent();
        }

        private void FCrush_Load(object sender, EventArgs e)
        {
            button1.Visible = false;
            button2.Visible = false;
            button3.Visible = false;
            button6.Visible = false;
            button7.Visible = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //object obj = null;
            //MessageBox.Show(obj.ToString());
            var filenames = Directory.GetFiles(@"D:/123/123/e");
            MessageBox.Show(filenames.Length.ToString());
        }



        private void button2_Click(object sender, EventArgs e)
        {
            IntPtr hwndPtr = WindowHelper.FindWindow(null, "Microsoft Visual C++ Runtime Library");
            int proId;
            var ret = WindowHelper.GetWindowThreadProcessId(hwndPtr, out proId);
            if (proId != 0)
            {
                var pro = Process.GetProcessById(proId);
                if (pro != null)
                {
                    try
                    {
                        pro.Kill();
                    }
                    catch (InvalidOperationException)
                    {

                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            IntPtr hwndPtr = WindowHelper.FindWindow(null, "Form1");
            int proId;
            var ret = WindowHelper.GetWindowThreadProcessId(hwndPtr, out proId);
            if (proId != 0)
            {
                var pro = Process.GetProcessById(proId);
                if (pro != null)
                {
                    try
                    {
                        pro.Kill();
                    }
                    catch (InvalidOperationException)
                    {

                    }
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
           

            Task.Factory.StartNew(XX);

            throw new Exception("nm");
        }

        private void XX()
        {
            if (this.InvokeRequired)
            {
                Thread.Sleep(5000);
                this.Invoke(new Action(this.XX));
            }
            else
            {
                IntPtr hwndPtr = WindowHelper.FindWindow(null, "FCrush");
                int proId;
                var ret = WindowHelper.GetWindowThreadProcessId(hwndPtr, out proId);
                if (proId != 0)
                {
                    var pro = Process.GetProcessById(proId);
                    if (pro != null)
                    {
                        try
                        {
                            var res = pro.Responding;
                            //pro.Kill();
                        }
                        catch (InvalidOperationException)
                        {

                        }
                    }
                }
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            while (true)
            {

            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            var windows = WindowHelper.FindWindows();
            Process pro;

            foreach (var window in windows)
            {
                pro = null;
                if (window.ProcessId > 0)
                {
                    pro = Process.GetProcessById(window.ProcessId);
                }

                if (pro != null)
                {
                    if (string.IsNullOrEmpty(pro.MainModule.FileName))
                    {
                        if (pro.StartInfo != null)
                        {
                            sb.AppendLine($@"{pro.Id} {window.Title} {pro.ProcessName} sf:{pro.StartInfo.FileName}");
                        }
                        else
                        {
                            sb.AppendLine($@"{pro.Id} {window.Title} {pro.ProcessName} pro.StartInfo=null");
                        }
                    }
                    else
                    {
                        sb.AppendLine($@"{pro.Id} {window.Title} {pro.ProcessName} mf:{pro.MainModule.FileName}");
                    }
                }
                else
                {
                    sb.AppendLine($@"       {window.Title} pro=null    {window.Hwnd.ToString()}");
                }
            }

            //for (int i = 0; i < windows.Count; i++)
            //{
            //    var window = windows[i];
            //    sb.AppendLine($@"{window.Title}  {window.Bounds.X}, {window.Bounds.Y}, {window.Bounds.Width}, {window.Bounds.Height}");
            //}
            string str = sb.ToString();

        }

        private void button7_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            var windows = WindowHelper.FindWindows(t => t.Title.Contains("Microsoft Visual C++ Runtime Library"));
            Process pro;

            foreach (var window in windows)
            {
                pro = null;
                if (window.ProcessId > 0)
                {
                    pro = Process.GetProcessById(window.ProcessId);
                }

                if (pro != null)
                {
                    if (string.IsNullOrEmpty(pro.MainModule.FileName))
                    {
                        if (pro.StartInfo != null)
                        {
                            sb.AppendLine($@"{pro.Id} {window.Title} {pro.ProcessName} sf:{pro.StartInfo.FileName}");
                        }
                        else
                        {
                            sb.AppendLine($@"{pro.Id} {window.Title} {pro.ProcessName} pro.StartInfo=null");
                        }
                    }
                    else
                    {
                        sb.AppendLine($@"{pro.Id} {window.Title} {pro.ProcessName} mf:{pro.MainModule.FileName}");
                    }
                }
                else
                {
                    sb.AppendLine($@"       {window.Title} pro=null    {window.Hwnd.ToString()}");
                }
            }

            //for (int i = 0; i < windows.Count; i++)
            //{
            //    var window = windows[i];
            //    sb.AppendLine($@"{window.Title}  {window.Bounds.X}, {window.Bounds.Y}, {window.Bounds.Width}, {window.Bounds.Height}");
            //}
            string str = sb.ToString();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                //"exception_qt.exe"
                //List<int> crushProcessIdList = this.GetWerfaultCrushProcessIdList();
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
            }
        }

        private List<int> GetWerfaultCrushProcessIdList()
        {
            List<int> crushProcessIdList = null;
            const string WERFAULT_PROCESS_NAME = "werfault";//Werfault.exe进程名称
            Process[] werfaultProcess = Process.GetProcessesByName(WERFAULT_PROCESS_NAME);
            foreach (var werfaultProces in werfaultProcess)
            {
                var werfaultCheckProcessId = this.GetWerfaultProcessId(werfaultProces.Id);
                if (werfaultCheckProcessId <= 0 ||
                    crushProcessIdList != null && crushProcessIdList.Contains(werfaultCheckProcessId))
                {
                    continue;
                }

                if (crushProcessIdList == null)
                {
                    crushProcessIdList = new List<int>();
                }
                crushProcessIdList.Add(werfaultCheckProcessId);
            }

            return crushProcessIdList;
        }

        /// <summary>
        /// 获取进程命令行信息
        /// </summary>
        /// <param name="pId"></param>
        /// <returns></returns>
        private int GetWerfaultProcessId(int werfaultProcessId)
        {
            try
            {
                using (ManagementObjectSearcher search = new ManagementObjectSearcher($"select CommandLine from Win32_Process where ProcessId={werfaultProcessId}"))
                //using (ManagementObjectSearcher search = new ManagementObjectSearcher($"select CommandLine from Win32_Process"))
                {
                    using (ManagementObjectCollection moc = search.Get())
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (ManagementObject mo in moc)
                        {
                            sb.Clear();
                            foreach (var pro in mo.Properties)
                            {
                                sb.Append(pro.Name);
                                sb.Append(':');
                                sb.AppendLine(pro.Value == null ? "null" : pro.Value.ToString());
                            }
                            string str = sb.ToString();
                            //werfault.exe /h /shared Global\\409752f6ec4c49a7a9aaaf24be671079 /t 10084 /p 29732
                            string commandLine = mo["CommandLine"].ToString();
                            if (string.IsNullOrWhiteSpace(commandLine))
                            {
                                continue;
                            }

                            const string PRO_PARA = "/p";
                            int index = commandLine.IndexOf(PRO_PARA);
                            if (index >= 0)
                            {
                                string pidStr = commandLine.Substring(index + PRO_PARA.Length).Trim();
                                index = pidStr.IndexOf(' ');
                                if (index > 0)
                                {
                                    pidStr = pidStr.Substring(0, index).Trim();
                                }

                                int pid;
                                if (int.TryParse(pidStr, out pid))
                                {
                                    return pid;
                                }
                            }
                            break;
                        }
                    }
                }
            }
            catch (ManagementException)
            { }
            catch (System.Runtime.InteropServices.COMException)
            { }

            return -1;
        }
    }





}
